//
//  SinaWBShareService.m
//  ShareCenter
//
//  Created by yutao on 14-2-23.
//  Copyright (c) 2014年 yutao. All rights reserved.
//

#import "SinaWBShareService.h"
#import "SNShareClient.h"
#import "ShareMessageInfo.h"
#import "ShareClientUserInfo.h"
#import "ShareClientOAuthInfo.h"
#import "JSONKit.h"

#define kGetSinaUserInfo    @"https://api.weibo.com/2/users/show.json"
#define kLogOutTag          @"logOut"
#define kGetUserInfoTag     @"getUserInfo"

#define kAccess_token       @"access_token"
#define kUserId             @"uid"
#define kExpires_in         @"expires_in"

#define kScreen_name        @"screen_name"
#define kProfile_image_url  @"profile_image_url"
#define kDescription        @"description"
#define kUid                @"id"

@implementation SinaWBShareService
static ShareCenterService * instance = nil;

+ (id)service
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)registerApplication
{
    [WeiboSDK registerApp:kSinaAppKey];
    [WeiboSDK enableDebugMode:YES];
    /*
#ifndef SN_RELEASE_VERSION
    [WeiboSDK enableDebugMode:YES];
#else
#endif
     */
}


- (BOOL)isAvailable
{
    /*
     * 必需有分享到新浪微博.
     * 运行时候才去确认是否有装新浪微博,
     * 新浪微博是否支持微博sdk
     */
    return YES;
}

- (void)login
{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kSinaAppRedirectURI;
    request.scope = @"all";
    [WeiboSDK sendRequest:request];

}

- (BOOL)logout
{
    [WeiboSDK logOutWithToken:[[ShareClientOAuthInfoSina defaultShareClientOAuth] oAuthValueForKey:kShareClientOAuthInfo_accessToken shareServiceType:kShareClientServiceTypeWeiBo] delegate:self withTag:kLogOutTag];
    return YES;
}

- (void)shareMessage:(ShareMessageInfo *)shareMessage
{
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageObjectWithShareMessage:shareMessage]];
//    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];
}

- (void)loadUserInfo
{
    if (![[ShareClientUserInfo defaultShareClientUser] hasUserInfoWithServiceType:kShareClientServiceTypeWeiBo]) {
        [self requestLoadUserInfo];
    }
    
}


- (void)requestLoadUserInfo
{
    ShareClientOAuthInfo *oAuthInfo = [[ShareClientOAuthInfo defaultShareClientOAuth] oAuthInfoWithServiceType:kShareClientServiceTypeWeiBo];
    [WBHttpRequest requestWithURL:kGetSinaUserInfo httpMethod:@"GET" params:@{kUserId:oAuthInfo.userIDKey,kAccess_token:oAuthInfo.accessTokenKey} delegate:self withTag:kGetUserInfoTag];
}


- (WBMessageObject *)messageObjectWithShareMessage:(ShareMessageInfo *) shareMessage
{
    WBMessageObject *message = [WBMessageObject message];
    
    if (shareMessage.title.length)
    {
        message.text = shareMessage.title;
    }
    
    if (shareMessage.imageData.length)
    {
        WBImageObject *image = [WBImageObject object];
        image.imageData = shareMessage.imageData;
        message.imageObject = image;
    }
    
    if (shareMessage.videoStreamUrl.length)
    {
        WBVideoObject *video = [WBVideoObject object];
        video.videoStreamUrl = shareMessage.videoStreamUrl;
        message.mediaObject = video;
    }
    
    return message;
}

- (BOOL)handleOpenURL:(NSURL *)url
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

#pragma mark -------WeiboSDKDelegate -----------------
/**
 接收并处理来至微博客户端程序的事件消息
 */
#pragma mark ==================================================

/**
 收到一个来自微博客户端程序的请求
 
 收到微博的请求后，第三方应用应该按照请求类型进行处理，处理完后必须通过 [WeiboSDK sendResponse:] 将结果回传给微博
 @param request 具体的请求对象
 */
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{

}

/**
 收到一个来自微博客户端程序的响应
 
 收到微博的响应后，第三方应用可以通过响应类型、响应的数据和 WBBaseResponse.userInfo 中的数据完成自己的功能
 @param response 具体的响应对象
 */
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        if (response.statusCode == WeiboSDKResponseStatusCodeSuccess)
        {
            [ShareCenterServiceHandler postNotificationName:SNShareServiceDidShareMessageNotification
                                            serviceType:SNShareClientTypeSinaWeibo];
        }
//        else if (response.statusCode == WeiboSDKResponseStatusCodeUserCancelInstall
//                 || response.statusCode == WeiboSDKResponseStatusCodeUnsupport)
//        {
//            
//            response.statusCode = WeiboSDKResponseStatusCodeSuccess;
//            
//        }
        else if (response.statusCode == WeiboSDKResponseStatusCodeSentFail)
        {
            [ShareCenterServiceHandler postNotificationName:SNShareServiceDidFailToShareMessageNotification
                                            serviceType:SNShareClientTypeSinaWeibo];
        }
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        
        if (response.statusCode == WeiboSDKResponseStatusCodeSuccess)
        {
            [ShareCenterServiceHandler postNotificationName:SNShareServiceDidLoginNotification serviceType:SNShareClientTypeSinaWeibo shareServiceOauthInfo:[self bundingOauthInfoWithWeiboResponse:response]];
            
            
            return;
            
        }
        else if (response.statusCode == WeiboSDKResponseStatusCodeAuthDeny)
        {
            [ShareCenterServiceHandler postNotificationName:SNShareServiceDidFailToLoginNotification
                                            serviceType:SNShareClientTypeSinaWeibo];
        }
        else if (response.statusCode == WeiboSDKResponseStatusCodeUserCancel)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:SNShareServiceDidCancelLoginNotification object:nil];
        }
        
    }
}


#pragma mark -------WBHttpRequestDelegate -----------------

/**
 接收并处理来自微博sdk对于网络请求接口的调用响应 以及openAPI
 如inviteFriend、logOutWithToken的请求
 */
#pragma mark ==================================================

/**
 收到一个来自微博Http请求的响应
 
 @param response 具体的响应对象
 */
- (void)request:(WBHttpRequest *)request didReceiveResponse:(NSURLResponse *)response
{
    
}

/**
 收到一个来自微博Http请求失败的响应
 
 @param error 错误信息
 */
- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error
{
    if ([request.tag isEqualToString:kGetSinaUserInfo]) {
        [ShareCenterServiceHandler postNotificationName:SNShareServiceDidFailToLoadUserInfoNotification serviceType:SNShareClientTypeSinaWeibo userInfo:nil];
    }else{
        //退出登录
    }
}

/**
 收到一个来自微博Http请求的网络返回
 
 @param result 请求返回结果
 */
- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    if ([request.tag isEqualToString:kGetUserInfoTag]) {
        [ShareCenterServiceHandler postNotificationName:SNShareServiceDidLoadUserInfoNotification serviceType:SNShareClientTypeSinaWeibo shareServiceUserInfo:[self bundingUserInfoWithResponsRes:result]];
        
    }else{
        //退出登录
    }
}

- (ShareClientOAuthInfoSina *)bundingOauthInfoWithWeiboResponse:(WBBaseResponse *)response
{
    ShareClientOAuthInfoSina *oAuthInfo = [ShareClientOAuthInfoSina defaultShareClientOAuth];
    oAuthInfo.accessTokenKey = [[response userInfo] objectForKey:kAccess_token];
    oAuthInfo.userIDKey = [[response userInfo] objectForKey:kUserId];
    oAuthInfo.expirationDateKey = [[response userInfo] objectForKey:kExpires_in];
    
    BOOL isSucc = [oAuthInfo saveOAuthInfo:oAuthInfo serviceType:kShareClientServiceTypeWeiBo];
    if (isSucc) {
        [self loadUserInfo];
    }
    
    return oAuthInfo;
}

- (ShareClientUserInfoSina *)bundingUserInfoWithResponsRes:(NSString *)result
{
    ShareClientUserInfoSina *userInfo = [ShareClientUserInfoSina defaultShareClientUser];
    userInfo.screenName = [[result objectFromJSONString] objectForKey:kScreen_name];
    userInfo.iconURL = [[result objectFromJSONString] objectForKey:kProfile_image_url];
    userInfo.userDescription = [[result objectFromJSONString] objectForKey:kDescription];
    userInfo.uid = [[[result objectFromJSONString] objectForKey:kUid] stringValue];
    userInfo.serviceType = kShareClientServiceTypeWeiBo;
    
    [userInfo saveUserInfo:userInfo serviceType:kShareClientServiceTypeWeiBo];
    
    return userInfo;
}

/**
 收到一个来自微博Http请求的网络返回
 
 @param data 请求返回结果
 */
- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
{

}


@end
